//
//  NSNotificationCenter+zll.m
//  移动监控
//
//  Created by Vincent on 2017/3/29.
//  Copyright © 2017年 Vincent. All rights reserved.
//

#import "NSNotificationCenter+zll.h"
#import <objc/runtime.h>



@interface NSNotificationCenter ()

//缓存观察者
@property(nonatomic,strong)NSMutableArray *observerArr;

@end


@implementation NSNotificationCenter(zll)


-(NSMutableArray *)observerArr{
    
    id tmarr = objc_getAssociatedObject(self, "zll_obser_arr");
    if(tmarr==nil){
        tmarr = [NSMutableArray new];
        objc_setAssociatedObject(self, "zll_obser_arr", tmarr, OBJC_ASSOCIATION_RETAIN);
    }
    
    return tmarr;
}


+(void)addObserverForName:(NSNotificationName)name object:(id)obj usingBlock:(void (^)(NSNotification *))handled{
    
    id observer = [[NSNotificationCenter defaultCenter] addObserverForName:name object:obj queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification * _Nonnull note) {
        
        if(handled){
            handled(note);
        }
    }];
    
    objc_setAssociatedObject(observer, [name UTF8String], obj, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    
    [[NSNotificationCenter defaultCenter].observerArr addObject:observer];
    
}


+(void)removeObserveByName:(NSNotificationName)name object:(id)obj{
    
    id observer = nil;
    for(id obsv in [NSNotificationCenter defaultCenter].observerArr){
        if(obj==objc_getAssociatedObject(obsv, [name UTF8String])){
            observer = obsv;
        }
    }
    if(observer){
        [[NSNotificationCenter defaultCenter].observerArr removeObject:observer];
        [[NSNotificationCenter defaultCenter] removeObserver:observer];
    }
}



@end


